#include "myqueue.h"
#include "stdlib.h"
#include<assert.h>
#include<printf.h>

queue* init_queue(queue* q){
    if (q == NULL){
        q = malloc(sizeof(queue));
        printf("initqueue q=%p\n", q);
    }
    q->first = NULL;
    q->last = NULL;
    assert(q != NULL);
    return q;
}

void push_queue(queue* q, void* data){
    if (q == NULL){
        assert(0);
    }
    assert(data != NULL);
    queuenode* node = malloc(sizeof(queuenode));
    node->data = data;
    node->prev = q->last;
    node->next = NULL;
    if (q->last != NULL){
        q->last->next = node;
    }
    q->last = node;
    if (q->first == NULL){
        q->first = node;
    }

}

void* pop_queue(queue* q){
    if (q == NULL){
        assert(0);
    }
    // else{
    //     printf("try pop from %p\n", q);
    // }
    if (q->first == NULL){
        return q->first;
    }
    queuenode* ret = q->first;
    void* data = ret->data;
    assert(ret != NULL);
    q->first = ret->next;

    free(ret);    
    if(q->first == NULL){
        q->last = NULL;
        return data;
    }
    q->first->prev = NULL;

    return data;
}